# -*- coding: utf-8 -*-
from xtattend.models import AttendanceManage
from xtattend.models import ProjectManage
from django.db.models import Count
from django.db import connection
from django.contrib.auth.models import User
import time
import logging

logger = logging.getLogger(__name__)


def get_month_list(year=time.strftime('%Y')):
    month_list = []
    for i in range(0, 12):
        month_list.append(year + '-' + str(i + 1).zfill(2))
    return month_list


def get_project_list():
    qs = ProjectManage.objects.all().values('project_name')
    project_list = []
    for pn in qs:
        project_list.append(pn.get('project_name'))
    return project_list


def get_user_list():
    qs = User.objects.filter(is_superuser=0).values('first_name')
    user_list = []
    for pn in qs:
        user_list.append(pn.get('first_name'))
    return user_list


def set_default_project_month_data():
    project_list = get_project_list()
    month_list = get_month_list()
    default_data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    tmp_list = []
    for i in range(len(project_list)):
        tmp_list.append({"project": project_list[i], 'data': dict(zip(month_list, default_data))})
    return tmp_list


def set_default_month_data():
    month_list = get_month_list()
    default_data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    return dict(zip(month_list, default_data))


def set_default_user_month_data():
    user_list = get_user_list()
    month_list = get_month_list()
    default_data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    tmp_list = []
    for i in range(len(user_list)):
        tmp_list.append({"user": user_list[i], 'data': dict(zip(month_list, default_data))})
    return tmp_list


def get_attend_with_user_by_all():
    """
    全年按个人加班趋势
    :return: dict
    """
    get_user_total_attend = AttendanceManage.objects.filter(applicant__is_superuser=0).values('applicant__first_name').annotate(
        Count('applicant__username'))
    ut_key_list = []
    ut_value_list = []
    for i in range(len(get_user_total_attend)):
        for k, v in get_user_total_attend[i].items():
            if k == 'applicant__first_name':
                ut_key_list.append(v)
            else:
                ut_value_list.append(v)
    user_total_dict = {'xAxis_data': ut_key_list, 'series_data': ut_value_list}
    logger.info("全年按个人加班趋势汇总结果为:%s" % user_total_dict)
    return user_total_dict


def get_attend_by_role():
    """
    全年按个人加班趋势
    :return: dict
    """
    get_role_total_attend = AttendanceManage.objects.filter(applicant__is_superuser=0).values('applicant__profile__role').annotate(
        Count('applicant__username'))
    role_key_list = []
    role_value_list = []
    for i in range(len(get_role_total_attend)):
        for k, v in get_role_total_attend[i].items():
            if k == 'applicant__profile__role':
                role_key_list.append(v)
            else:
                role_value_list.append(v)
    role_total_dict = {'xAxis_data': role_key_list, 'series_data': role_value_list}
    logger.info("全年按个人加班趋势汇总结果为:%s" % role_total_dict)
    return role_total_dict

def get_attend_with_project_by_all():
    """
    全年按项目加班趋势
    :return:
    """
    get_project_total_attend = AttendanceManage.objects.values('project__project_name').annotate(
        Count('project__project_name'))
    pt_key_list = []
    pt_value_list = []
    for ipt in range(len(get_project_total_attend)):
        for k, v in get_project_total_attend[ipt].items():
            if k == 'project__project_name':
                pt_key_list.append(v)
            else:
                pt_value_list.append(v)
    project_total_dict = {'xAxis_data': pt_key_list, 'series_data': pt_value_list}
    return project_total_dict


def get_attend_every_by_month():
    """
    全年各月份加班趋势
    :return:
    """
    get_every_month_attend = AttendanceManage.objects.extra(
        {'month': connection.ops.date_trunc_sql('month', 'start_time')}).values('month').annotate(
        numbers=Count('applicant__username')).order_by('month')
    em_key_list = []
    em_value_list = []

    default_month_data = set_default_month_data()

    for i in range(len(get_every_month_attend)):
        for key, value in default_month_data.items():
            if key == str(get_every_month_attend[i].get('month'))[:-3]:
                default_month_data[key] = get_every_month_attend[i].get('numbers')

    month_total_dict = {'xAxis_data': list(default_month_data.keys()), 'series_data': list(default_month_data.values())}
    return month_total_dict


def get_attend_by_month_with_project():
    month_project_attend = AttendanceManage.objects.extra(
        {'month': connection.ops.date_trunc_sql('month', 'start_time')}).values('month',
                                                                                'project__project_name').annotate(
        numbers=Count('project__project_name')).order_by('month')

    default = set_default_project_month_data()
    for mpa in range(len(month_project_attend)):
        for dt in range(len(default)):
            qs_month = str(month_project_attend[mpa].get('month'))[:-3]

            for key, value in default[dt].get('data').items():
                if qs_month == key and month_project_attend[mpa].get('project__project_name') == default[dt].get('project'):
                    default[dt].get('data')[key] = month_project_attend[mpa].get('numbers')

    month_list = get_month_list()
    project_list = get_project_list()

    result = []
    for i in range(len(default)):
        result.append({'project': default[i].get('project'), 'data': list(default[i].get('data').values())})
    return {'legend': project_list, 'xAxis_data': month_list, 'series': result}


def get_attend_by_month_with_user():
    month_user_attend = AttendanceManage.objects.extra(
        {'month': connection.ops.date_trunc_sql('month', 'start_time')}).values('month',
                                                                                'applicant__first_name').annotate(
        numbers=Count('applicant__username')).order_by('month')

    default = set_default_user_month_data()
    for mpa in range(len(month_user_attend)):
        for dt in range(len(default)):
            qs_month = str(month_user_attend[mpa].get('month'))[:-3]

            for key, value in default[dt].get('data').items():
                if qs_month == key and month_user_attend[mpa].get('applicant__first_name') == default[dt].get('user'):
                    default[dt].get('data')[key] = month_user_attend[mpa].get('numbers')

    month_list = get_month_list()
    user_list = get_user_list()

    result = []
    for i in range(len(default)):
        result.append({'user': default[i].get('user'), 'data': list(default[i].get('data').values())})
    return {'legend': user_list, 'xAxis_data': month_list, 'series': result}

